<?php

namespace App\Console\Commands\Common;

use App\Models\Common\CityResidencePriceModel;
use App\Models\Common\CityTerritorialBoundaryModel;
use App\Remote\Bk\BkRemote;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;

class GenerateNationalHousePrice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'common:generateNationalHousePrice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成全国房价入库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    const REQUEST_TYPE_1 = "district";
    const REQUEST_TYPE_2 = "bizcircle";
    const REQUEST_TYPE_3 = "community";


    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        CityTerritorialBoundaryModel::query()
                                    ->where("level", CityTerritorialBoundaryModel::LEVEL_CITY)
                                    ->where("runStatus", "=", 0)
                                    ->get()
                                    ->each(function (CityTerritorialBoundaryModel $territorialBoundaryModel) {
                                        $this->info("【城市名称 : {$territorialBoundaryModel->id} {$territorialBoundaryModel->name}】");
                                        list(
                                            $maxLongitude,
                                            $maxLatitude,
                                            $minLongitude,
                                            $minLatitude
                                            ) = self::getAreaBorderline($territorialBoundaryModel->polyline);

                                        $districtResponse = BkRemote::bubbleList(
                                            $territorialBoundaryModel->adcode,
                                            $maxLongitude, $maxLatitude,
                                            $minLongitude, $minLatitude,
                                            self::REQUEST_TYPE_1
                                        );

                                        if (!empty($districtResponse["data"]["bubbleList"])) {
                                            foreach ($districtResponse["data"]["bubbleList"] as $bubbleList) {
                                                list($maxLongitude, $maxLatitude, $minLongitude, $minLatitude) = self::getAreaBorderline($bubbleList["border"]);
                                                $this->info(vsprintf("【城市名称 : {$territorialBoundaryModel->name}】 区 - 【名称 : %s】【经度 : %s】【纬度 : %s】",
                                                    [
                                                        $bubbleList["name"],
                                                        $bubbleList["longitude"],
                                                        $bubbleList["latitude"]
                                                    ]));

                                                $bizCircleResponse = BkRemote::bubbleList(
                                                    $territorialBoundaryModel->adcode,
                                                    $maxLongitude,
                                                    $maxLatitude, $minLongitude, $minLatitude,
                                                    self::REQUEST_TYPE_2
                                                );

                                                if (!empty($bizCircleResponse["data"]["bubbleList"])) {
                                                    foreach ($bizCircleResponse["data"]["bubbleList"] as $bizCircleBubbleList) {
                                                        list($maxLongitude, $maxLatitude, $minLongitude, $minLatitude) = self::getAreaBorderline($bizCircleBubbleList["border"]);
                                                        $this->info(vsprintf("【城市名称 : {$territorialBoundaryModel->name}】 商圈 - 【名称 : %s】【经度 : %s】【纬度 : %s】",
                                                            [
                                                                $bizCircleBubbleList["name"],
                                                                $bizCircleBubbleList["longitude"],
                                                                $bizCircleBubbleList["latitude"]
                                                            ]));

                                                        $communityResponse = BkRemote::bubbleList(
                                                            $territorialBoundaryModel->adcode,
                                                            $maxLongitude,
                                                            $maxLatitude, $minLongitude,
                                                            $minLatitude,
                                                            self::REQUEST_TYPE_3);

                                                        if (!empty($communityResponse["data"]["bubbleList"])) {
                                                            foreach ($communityResponse["data"]["bubbleList"] as $communityBubbleList) {
                                                                try {
                                                                    CityResidencePriceModel::query()
                                                                                           ->insert(array_merge(
                                                                                               [
                                                                                                   "name"            => $communityBubbleList["name"],
                                                                                                   "centerLongitude" => $communityBubbleList["longitude"],
                                                                                                   "centerLatitude"  => $communityBubbleList["latitude"],
                                                                                                   "price"           => $communityBubbleList["price"],
                                                                                                   "border"          => $communityBubbleList["border"],
                                                                                                   "bkId"            => $communityBubbleList["id"],
                                                                                               ],
                                                                                               ["createdAt" => time()]));


                                                                    $this->info("【城市名称 : {$territorialBoundaryModel->name}】 【小区名称 {$communityBubbleList["id"]} : {$communityBubbleList["name"]}】成功");
                                                                } catch (QueryException $queryException) {
                                                                    if ($queryException->getCode() != "23000") {
                                                                        $this->error("【城市名称 : {$territorialBoundaryModel->name}】 【小区名称 {$communityBubbleList["id"]} : {$communityBubbleList["name"]}】失败");
                                                                        $this->error($queryException->getMessage());
                                                                        Log::error($queryException->getMessage());
                                                                    }
                                                                } catch (\Exception $exception) {
                                                                    $this->error("【城市名称 : {$territorialBoundaryModel->name}】 【小区名称 {$communityBubbleList["id"]} : {$communityBubbleList["name"]}】失败");
                                                                    $this->error($exception->getMessage());
                                                                    Log::error($exception->getMessage());
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        $territorialBoundaryModel->runStatus = 1;
                                        $territorialBoundaryModel->save();
                                    });

//        list($maxLongitude, $maxLatitude, $minLongitude, $minLatitude) = [
//            "116.73445042767183",
//            "40.106319397233676",
//            "116.07329757232806",
//            "39.72291790076397",
//        ];
//            self::getAreaBorderline($border);

//        maxLatitude: 40.106319397233676
//minLatitude: 39.72291790076397
//maxLongitude: 116.73445042767183
//minLongitude: 116.07329757232806

        $latitudeDistance  = 3000;
        $longitudeDistance = 4000;
//        $districtResponse  = BkRemote::bubbleList(110000, $maxLongitude, $maxLatitude, $minLongitude, $minLatitude,
//            self::REQUEST_TYPE_1);
//
//        foreach ($districtResponse["data"]["bubbleList"] as $bubbleList) {
//            list($maxLongitude, $maxLatitude, $minLongitude, $minLatitude) = self::getAreaBorderline($bubbleList["border"]);
//            $this->info(vsprintf("区 - 【名称 : %s】【经度 : %s】【纬度 : %s】", [
//                $bubbleList["name"],
//                $bubbleList["longitude"],
//                $bubbleList["latitude"]
//            ]));
//
//            $bizCircleResponse = BkRemote::bubbleList(110000, $maxLongitude, $maxLatitude, $minLongitude, $minLatitude,
//                self::REQUEST_TYPE_2);
//
//            foreach ($bizCircleResponse["data"]["bubbleList"] as $bizCircleBubbleList) {
//                list($maxLongitude, $maxLatitude, $minLongitude, $minLatitude) = self::getAreaBorderline($bizCircleBubbleList["border"]);
//                $this->info(vsprintf("商圈 - 【名称 : %s】【经度 : %s】【纬度 : %s】", [
//                    $bizCircleBubbleList["name"],
//                    $bizCircleBubbleList["longitude"],
//                    $bizCircleBubbleList["latitude"]
//                ]));
//
//                $communityResponse = BkRemote::bubbleList(110000, $maxLongitude, $maxLatitude, $minLongitude,
//                    $minLatitude,
//                    self::REQUEST_TYPE_3);
//
//                if (!empty($communityResponse["data"]["bubbleList"])) {
//                    foreach ($communityResponse["data"]["bubbleList"] as $communityBubbleList) {
//                        $this->info(vsprintf("小区 - 【名称 : %s】【经度 : %s】【纬度 : %s】【价格 : %s】", [
//                            $communityBubbleList["name"],
//                            $communityBubbleList["longitude"],
//                            $communityBubbleList["latitude"],
//                            $communityBubbleList["priceStr"]
//                        ]));
//                    }
//                }
//            }
//
//        }


        return parent::SUCCESS;
    }

    /**
     * 获取边界经纬度
     *
     * @param string $border
     * @return array
     */
    public static function getAreaBorderline(string $border): array
    {
        $longitudeMap = [];
        $latitudeMap  = [];
        collect(explode(";", $border))->each(function ($v) use (&$longitudeMap, &$latitudeMap) {
            list($longitude, $latitude) = explode(",", $v);
            array_push($longitudeMap, $longitude);
            array_push($latitudeMap, $latitude);
        });

        return [
            max($longitudeMap),
            max($latitudeMap),
            min($longitudeMap),
            min($latitudeMap)
        ];
    }
}
